package com.carl.lambda.simpleLambda.Lambda3;


/*
 * Java8 内置的四大核心函数式接口
 *
 * Consumer<T> : 消费型接口
 * 		void accept(T t);
 *
 * Supplier<T> : 供给型接口
 * 		T get();
 *
 * Function<T, R> : 函数型接口
 * 		R apply(T t);
 *
 * Predicate<T> : 断言型接口
 * 		boolean test(T t);
 *
 */

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class LambdaTest {

    //Consumer<T> 消费型接口 :
    @Test
    public void test1(){
        happy(10000, (t) -> System.out.println("lambda学了" + t + "次"));
    }

    public void happy(int times, Consumer<Integer> con){
        con.accept(times);
    }

    //Supplier<T> : 供给型接口
    //需求：产生指定个数的整数，并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> supplier){
        List<Integer> list = new ArrayList<>();
        for (int i = 0;i<num;i++){
            Integer n = supplier.get();
            list.add(n);
        }
        return list;
    }
    @Test
    public void test2(){
        List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
        for (Integer num : numList) {
            System.out.print(num+",");
        }
    }

    //Function<T, R> : 函数型接口
    //处理字符串
    public String strHandler(String str, Function<String,String> function){
        return function.apply(str);
    }
    @Test
    public void strHandlerTest(){
        String newStr = strHandler("\t\t\tlambda真的简单", String::trim);
        System.out.println(newStr);
    }

    //Predicate<T> : 断言型接口
    //将满足条件的字符串，放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pre){
        List<String> stringList = new ArrayList<>();
        for (String s : list) {
            if (pre.test(s)) stringList.add(s);
        }
        return stringList;
    }

    @Test
    public void strTest(){
        List<String> list = Arrays.asList("Hello", "你好", "Lambda", "www", "ok");
        List<String> stringList = filterStr(list, (s) -> s.length() > 3);
        for (String s : stringList) {
            System.out.println(s);
        }
    }





}
